<template>
  <view class="login-container">
    <!-- 顶部区域 -->
    <view class="top-section">
      <view class="back-btn" @click="goBack">
        <u-icon name="arrow-left" color="#666" size="20"></u-icon>
      </view>
      <view class="language-switch">
        <text class="language-text">简体中文</text>
        <u-icon name="arrow-down" color="#666" size="14"></u-icon>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- Logo和标题区域 -->
      <view class="header-section">
        <image class="logo-image" src="/static/logo.png" mode="aspectFit"></image>
        <text class="app-title">社交圈子</text>
      </view>

      <!-- 登录表单 -->
      <view class="form-container">
        <!-- 手机号/用户名输入框 -->
        <view class="input-group">
          <u-input
            v-model="loginForm.username"
            placeholder="手机号/用户名"
            class="login-input"
            border="none"
            :custom-style="inputStyle"
            prefixIcon="account"
            prefixIconStyle="color: #666; font-size: 20px; margin-right: 10px;"
            @blur="validateUsername"
          />
          <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
        </view>

        <!-- 密码输入框 -->
        <view class="input-group">
          <u-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            class="login-input"
            border="none"
            :custom-style="inputStyle"
            prefixIcon="lock"
            prefixIconStyle="color: #666; font-size: 20px; margin-right: 10px;"
            @blur="validatePassword"
          />
          <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
        </view>

        <!-- 验证码输入框 -->
        <view class="input-group" v-if="captchaEnabled">
          <view class="captcha-container">
            <u-input
              v-model="loginForm.code"
              placeholder="验证码"
              class="login-input captcha-input"
              border="none"
              :custom-style="inputStyle"
              prefixIcon="shield"
              prefixIconStyle="color: #666; font-size: 20px; margin-right: 10px;"
            />
            <image
              class="captcha-image"
              :src="codeUrl"
              @click="getCode"
            />
          </view>
        </view>

        <!-- 登录按钮 -->
        <button
          class="login-btn"
          :class="{ 'loading': loading }"
          @click="handleLogin"
          :disabled="loading"
        >
          <u-loading-icon v-if="loading" color="white" size="20"></u-loading-icon>
          <text class="button-text">{{ loading ? '登录中...' : '登录' }}</text>
        </button>

        <!-- 暂不登录按钮 -->
        <view class="skip-login-btn" @click="handleSkipLogin">
          <text class="skip-btn-text">暂不登录，先看看</text>
        </view>

        <!-- 其他选项 -->
        <view class="options-row">
          <view class="remember-me">
            <u-checkbox-group v-model="checkboxValue" @change="handleRememberMeChange">
              <u-checkbox
                name="rememberMe"
                :checked="loginForm.rememberMe"
                active-color="#4facfe"
                size="14"
              >
                <text class="remember-text">记住密码</text>
              </u-checkbox>
            </u-checkbox-group>
          </view>
          <text class="forgot-password" @click="handleForgotPassword">忘记密码？</text>
        </view>
      </view>

      <!-- 第三方登录 -->
      <view class="social-login">
        <view class="divider-container">
          <view class="divider-line"></view>
          <text class="divider-text">其他登录方式</text>
          <view class="divider-line"></view>
        </view>

        <view class="social-buttons">
          <view class="social-btn wechat-btn" @click="handleWechatLogin">
            <u-icon name="weixin-fill" color="#1AAD19" size="28"></u-icon>
            <text class="social-btn-text">微信</text>
          </view>
          <view class="social-btn qq-btn" @click="handleQQLogin">
            <u-icon name="qq-fill" color="#12B7F5" size="28"></u-icon>
            <text class="social-btn-text">QQ</text>
          </view>
          <view class="social-btn sms-btn" @click="handleSMSLogin">
            <u-icon name="chat" color="#ff4757" size="28"></u-icon>
            <text class="social-btn-text">短信</text>
          </view>
        </view>
      </view>

      <!-- 底部区域 -->
      <view class="bottom-section">
        <text class="register-text">还没有账户？</text>
        <text class="register-link" @click="handleRegister">立即注册</text>
      </view>
    </view>

  </view>
</template>

<script>
import { login, getCodeImg } from "@/api/login"
import { getToken, setToken, removeToken } from "@/utils/auth"

export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        code: '',
        uuid: '',
        rememberMe: false
      },
      loading: false,
      captchaEnabled: true,
      codeUrl: '',
      errors: {},
      checkboxValue: [],
      inputStyle: {
        backgroundColor: '#f8f9fa',
        borderRadius: '12px',
        padding: '15px 20px',
        fontSize: '16px',
        color: '#333',
        border: '1px solid #e9ecef'
      }
    }
  },
  onLoad() {
    this.getCode()
    this.getCookie()
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      })
    },

    // 获取验证码
    async getCode() {
      try {
        const res = await getCodeImg()

        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      } catch (error) {
        console.error('获取验证码失败:', error)
        this.showToast('获取验证码失败', 'error')
      }
    },

    // 刷新验证码
    refreshCaptcha() {
      if (this.captchaEnabled) {
        this.loginForm.code = '' // 清空验证码输入
        this.getCode()
      }
    },

    // 获取Cookie
    getCookie() {
      const username = uni.getStorageSync('username')
      const password = uni.getStorageSync('password')
      const rememberMe = uni.getStorageSync('rememberMe')

      this.loginForm = {
        username: username || '',
        password: password || '',
        rememberMe: rememberMe || false,
        code: '',
        uuid: ''
      }
      
      // 设置checkbox的初始值
      this.checkboxValue = this.loginForm.rememberMe ? ['rememberMe'] : []
    },

    // 处理记住密码变化
    handleRememberMeChange(e) {
      this.loginForm.rememberMe = e.includes('rememberMe')
      this.checkboxValue = e
    },

    // 表单验证
    validateUsername() {
      if (!this.loginForm.username) {
        this.errors.username = '请输入用户名或手机号'
        return false
      }
      if (this.loginForm.username.length < 2) {
        this.errors.username = '用户名至少2个字符'
        return false
      }
      this.errors.username = ''
      return true
    },

    validatePassword() {
      if (!this.loginForm.password) {
        this.errors.password = '请输入密码'
        return false
      }
      if (this.loginForm.password.length < 6) {
        this.errors.password = '密码至少6个字符'
        return false
      }
      this.errors.password = ''
      return true
    },

    // 登录处理
    async handleLogin() {
      // 表单验证
      const isUsernameValid = this.validateUsername()
      const isPasswordValid = this.validatePassword()

      if (!isUsernameValid || !isPasswordValid) {
        this.showToast('请检查输入信息', 'error')
        return
      }

      if (this.captchaEnabled && !this.loginForm.code) {
        this.showToast('请输入验证码', 'error')
        return
      }

      this.loading = true

      try {
        this.$store.dispatch('Login', this.loginForm).then(() => {

          this.$modal.closeLoading()
          this.loginSuccess()
        }).catch(() => {
          if (this.captchaEnabled) {
            this.refreshCaptcha()
          }
        })
        /*const res = await login(this.loginForm.username, this.loginForm.password, this.loginForm.code, this.loginForm.uuid)

        if (res.code === 200) {
          // 保存token
          setToken(res.token)

          // 记住密码
          if (this.loginForm.rememberMe) {
            uni.setStorageSync('username', this.loginForm.username)
            uni.setStorageSync('password', this.loginForm.password)
            uni.setStorageSync('rememberMe', true)
          } else {
            uni.removeStorageSync('username')
            uni.removeStorageSync('password')
            uni.removeStorageSync('rememberMe')
          }

          this.showToast('登录成功', 'success')

          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            this.$tab.reLaunch('/pages/index')
          }, 1500)
        } else {
          this.showToast(res.msg || '登录失败', 'error')
          // 登录失败时刷新验证码
          this.refreshCaptcha()
        }*/
      } catch (error) {
        console.error('登录错误:', error)
        this.showToast('网络错误，请稍后重试', 'error')
        // 网络错误时刷新验证码
        this.refreshCaptcha()
      } finally {
        this.loading = false
      }
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      // 设置用户信息
      this.$store.dispatch('GetInfo').then(res => {
        this.$tab.reLaunch('/pages/index')
      })
    },
    // 跳转注册
    handleRegister() {
      this.$tab.navigateTo('/pages/register')
    },

    // 忘记密码
    handleForgotPassword() {
      this.showToast('请联系管理员重置密码', 'info')
    },

    // 微信登录
    handleWechatLogin() {
      this.showToast('微信登录功能开发中', 'info')
    },

    // QQ登录
    handleQQLogin() {
      this.showToast('QQ登录功能开发中', 'info')
    },

    // 短信登录
    handleSMSLogin() {
      this.showToast('短信登录功能开发中', 'info')
    },

    // 暂不登录，直接跳转首页
    handleSkipLogin() {
      console.log('点击暂不登录按钮')
      uni.switchTab({
        url: '/pages/index',
        success: function() {
          console.log('跳转成功')
        },
        fail: function(err) {
          console.error('跳转失败:', err)
          // 如果 switchTab 失败，尝试使用 reLaunch
          uni.reLaunch({
            url: '/pages/index'
          })
        }
      })
    },

    // 显示提示
    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 0 30px;
}

.top-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 50px 0 20px;

  .back-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 20px;
    background: #f8f9fa;
  }

  .language-switch {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 20px;

    .language-text {
      color: #666;
      font-size: 14px;
      margin-right: 5px;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px 0;
}

.header-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 50px;

  .logo-image {
    width: 80px;
    height: 80px;
    margin-bottom: 15px;
  }

  .app-title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
  }
}

.form-container {
  margin-bottom: 40px;

  .input-group {
    margin-bottom: 20px;

    .error-text {
      font-size: 12px;
      color: #ff4757;
      margin-top: 5px;
      margin-left: 5px;
    }
  }

  .captcha-container {
    display: flex;
    align-items: center;
    gap: 10px;

    .captcha-input {
      flex: 1;
    }

    .captcha-image {
      width: 100px;
      height: 50px;
      border-radius: 12px;
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
    }
  }

  .login-btn {
    width: 100%;
    height: 50px;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border-radius: 12px;
    color: #ffffff;
    font-size: 16px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 30px 0 15px;
    border: none;
    box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
    transition: all 0.3s ease;

    &.loading {
      opacity: 0.8;
    }

    .button-text {
      margin-left: 8px;
    }

    &:active {
      transform: translateY(2px);
      box-shadow: 0 2px 10px rgba(79, 172, 254, 0.2);
    }
  }

  .skip-login-btn {
    width: 100%;
    height: 45px;
    background: transparent;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    color: #666;
    font-size: 15px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    cursor: pointer;

    .skip-btn-text {
      color: #666;
    }

    &:active {
      background: #f8f9fa;
      border-color: #4facfe;
      
      .skip-btn-text {
        color: #4facfe;
      }
    }
  }

  .options-row {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .remember-text {
      font-size: 14px;
      color: #666;
      margin-left: 5px;
    }

    .forgot-password {
      font-size: 14px;
      color: #4facfe;
    }
  }
}

.social-login {
  margin-top: 20px;

  .divider-container {
    display: flex;
    align-items: center;
    margin-bottom: 30px;

    .divider-line {
      flex: 1;
      height: 1px;
      background: #e9ecef;
    }

    .divider-text {
      margin: 0 15px;
      font-size: 14px;
      color: #999;
    }
  }

  .social-buttons {
    display: flex;
    justify-content: space-around;

    .social-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 15px;
      border-radius: 12px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: #e9ecef;
      }

      .social-btn-text {
        font-size: 12px;
        color: #666;
        margin-top: 8px;
        font-weight: 500;
      }

      &.wechat-btn {
        .social-btn-text {
          color: #1AAD19;
        }
      }

      &.qq-btn {
        .social-btn-text {
          color: #12B7F5;
        }
      }

      &.sms-btn {
        .social-btn-text {
          color: #ff4757;
        }
      }
    }
  }
}

.bottom-section {
  margin-top: auto;
  text-align: center;
  padding: 20px 0 40px;

  .register-text {
    font-size: 14px;
    color: #999;
  }

  .register-link {
    font-size: 14px;
    color: #4facfe;
    font-weight: 500;
    margin-left: 5px;
  }
}
</style>
